<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@page import="java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.File" %>
<%@ page import = "java.io.InputStream" %>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Role</title>
	
	<link rel="stylesheet" type="text/css" href="css/stylev2.css" /> 
	<link rel="stylesheet" type="text/css" href="css/student-system.css" />
	<link rel="stylesheet" type="text/css" href="css/menubar.css" />
	<link rel="stylesheet" type="text/css" href="css/frame.css" />
	
	<style type="text/css">
		a {
	      text-decoration:none;
	   }
	</style>
	
	<script type="text/javascript">
		function add_role() {
			document.location.href = "admin_role_add.jsp";
		}
		
		function deleteButton(id) {
			var roleName = (document.getElementById('roleName' + id)).innerHTML.trim();
			var roleId = document.getElementById('roleId' + id).value;
						
			if (confirm("คุณต้องการจะลบข้อมูล " + roleName) == true) {
				/* AJAX */
				var xmlhttp;
				
				if(window.XMLHttpRequest) {
					// code for IE7+, Firefox, Chrome, Opera, Safari
					xmlhttp = new XMLHttpRequest();
				}
				else {
					// code for IE6, IE5
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				
				xmlhttp.onreadystatechange = function() {
					if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
						var result = xmlhttp.responseText;

						if(result == "success") {
							window.location.reload();
							alert("สำเร็จ");////////test///////
						}
						else if(result == "fail") {
							alert("ไม่สามารถลบ "+roleName+" ได้ เนื่องจากข้อมูลนี้มีการใช้งานอยู่");////////test///////
						}
						else {
							alert("ไม่สามารถลบข้อมูลได้");////////test///////
						}
						
					}
				}
				
				xmlhttp.open("POST", "admin_role_delete.jsp?roleId="+roleId, true);
				xmlhttp.send();
		    } else {  }
		}
	</script>
</head>
<body>

<%
	// get session
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
	
	// check session
		if (htp_session == null || htp_session.getAttribute("sUser") == null) {
		    // Forward the control to login.jsp if authentication fails or session expires
		    request.getRequestDispatcher("/login.jsp").forward(request,
		        response);
		}
		if(!"admin".equals(htp_session.getAttribute("sUser"))){%>
			<script>alert("This user dont have PERMISSION to access this zone.");</script>
			<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=system_select.jsp"> 	
	<%}
	
	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}
	
	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps );
	
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
	/* find role in database */
	List<Role> role = new ArrayList<Role>();
	
	try {			   
		ResultSet rs = connect.createStatement().executeQuery("SELECT role_id, role_name, permission, R.system_id, system_name, system_name_th " 
				+ " FROM role R, system S " 
				+ " WHERE R.system_id=S.system_id "
				+ " ORDER BY role_name");
		
		while(rs.next()) {
			Role rol = new Role();
			
			rol.setRoleId(rs.getInt("role_id"));
			rol.setRoleName(rs.getString("role_name"));
			rol.setPermission(rs.getString("permission"));
			rol.setSystemId(rs.getInt("system_id"));
			rol.setSystemName(rs.getString("system_name"));
			rol.setSystemNameTH(rs.getString("system_name_th"));
			
			role.add(rol);
		}
		
	} catch (SQLException e) {
		e.printStackTrace();
	}
	
	connect.close();
%>

	<div id="page-wrap">
			<div id="inside">
				<table border="0">
					<tr style="font-size:24px">
						<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
							<div id="header_banner-2"></div>
						</td>
						
						<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
							<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
							<a href="logout.jsp"><p align="right"><label style="cursor: pointer;"><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
						</td>
					</tr>
				</table>
				
			 <ul id="drop-nav">
		        <li><a href="admin_home.jsp">หน้าแรก</a></li>
		        
		        <li>
		            <a href="">องค์กร &nbsp; &#9662;</a>
		            <ul>
		                <li><a href="admin_department.jsp">ภาควิชา</a></li>
		                <li><a href="admin_workgroup.jsp">หน่วยงาน</a></li>
		            </ul>
		        </li>
		        <li style="background-color: #FFFFFF; padding-top: 13px; text-align: center;  border-bottom-color: #FFFFFF; border-left-color: #FFFFFF; border-right-color: #FFFFFF">
		        	<font color="#273b80" size="4.8px" face="Tahoma">หน้าที่</font>
		        </li>
		        <li><a href="admin_account.jsp">บัญชีผู้ใช้</a></li>
		        <li>
		        	<a href="">บุคคล &nbsp; &#9662;</a>
		        	<ul>
		                <li><a href="admin_lecturer.jsp">อาจารย์</a></li>
		                <li><a href="admin_employee.jsp">บุคลากร</a></li>
		            </ul>
		        </li>
		        <li><a href="admin_entrance.jsp">ระบบเข้าศึกษา</a></li>
		        <li><a href="admin_status.jsp">สถานะของนักศึกษา</a></li>
		        <li>
		        	<a href="">ตำแหน่ง &nbsp; &#9662;</a>
		        	<ul>
		                <li><a href="admin_educate_position.jsp">ตำแหน่งทางวิชาการ</a></li>
		                <li><a href="admin_management_position.jsp">ตำแหน่งบริหาร</a></li>
		            </ul>
		        </li>
		    </ul>
    
						<div id="main-content-ac">
							
							<br/><br/><br/><br/>
						
							<table style="border: 0px">
								<tr style="border: 0px">
									<td style="border: 0px">
										<div class="imageFrame">หน้าที่</div>
									</td>
									<td style="border: 0px">
										<div style="margin-top: 30px; margin-left: 20px; cursor: pointer;">
											<span title="เพิ่มข้อมูล">
												<img src="image/add_icon.png" width="40px" height="40px" onclick="add_role()">
											</span>	
										</div>
									</td>
								</tr>
							</table>
							
							<br/><br/><br/><br/>
							<center>
								<div class="CSSTableGenerator">
									<table border="1">
										  <tr style="font-size:24px">
											<td><center><strong>หน้าที่</strong></center></td>
											<td><center><strong>ระบบ</strong></center></td>
											<td><center><strong>Permission</strong></center></td>
											<td>&nbsp;</td>
											<td>&nbsp;</td>
										  </tr>
<%
						int roleCount = 1;
						for(Role ro : role) {
							String permission = "";
							char[] per = ro.getPermission().toCharArray();
							int checkPer = 0;
							
							if(per[0] == '1') {
								permission = permission + "Add";
								checkPer++;
							}
							if(per[1] == '1') {
								if(checkPer > 0) {
									permission = permission + ", Edit";
								}
								else {
									permission = permission + "Edit";
								}
								checkPer++;
							}
							if(per[2] == '1') {
								if(checkPer > 0) {
									permission = permission + ", Read";
								}
								else {
									permission = permission + "Read";
								}
								checkPer++;
							}
							if(per[3] == '1') {
								if(checkPer > 0) {
									permission = permission + ", Delete";
								}
								else {
									permission = permission + "Delete";
								}
								checkPer++;
							}
%>
										  <tr style="font-size:20px" id="role<%=roleCount%>">
										  	<form id="form<%=roleCount%>" name="form<%=roleCount%>" method="post" action="admin_role_edit.jsp">
										  	
										  		<input type="hidden" id="roleId" name="roleId" value="<%=ro.getRoleId()%>" />
										  		<input type="hidden" id="roleId<%=roleCount%>" name="roleId<%=roleCount%>" value="<%=ro.getRoleId()%>" />
										  		
										  		<input type="hidden" id="roleName" name="roleName" value="<%=ro.getRoleName()%>" />
												<td id="roleName<%=roleCount%>" name="roleName<%=roleCount%>">
													<%=ro.getRoleName()%>
												</td>
												
												<input type="hidden" id="systemId" name="systemId" value="<%=ro.getSystemId()%>" />
												
												<input type="hidden" id="systemName" name="systemName" value="<%=ro.getSystemNameTH()%>" />
												<td id="systemName<%=roleCount%>" name="systemName<%=roleCount%>">
													<%=ro.getSystemNameTH()%>
												</td>
												
												<input type="hidden" id="permissionText" name="permissionText" value="<%=ro.getPermission()%>" />
												<td id="permissionText<%=roleCount%>" name="permissionText<%=roleCount%>">
													<%=permission%>
												</td>
												<td>
													<center><span title="แก้ไขข้อมูล">
														<input type="image" src="image/edit_icon.png" height="30px" width="30px" />
													</span></center>
												</td>
											</form>
												<td>
													<center><span title="แก้ไขข้อมูล">
														<input type="image" src="image/delete_icon.png" height="30px" width="30px"  onclick="deleteButton('<%=roleCount%>')" />
													</span></center>
												</td>              
										  </tr>
<%
							roleCount++;
						}
%>
									</table>
								</div>
							</center>
						<br><br><br>
						
					<div style="clear: both;"></div>
						<div id="footer"></div>
			</div>		
						<div style="clear: both;"></div>		
    </div>

</body>
</html>